<template>
  <div id="body">
    <div id="header">
      <div class="back" @click="handleBackPage">
        <van-icon name="arrow-left" />
      </div>
      <div class="title">购物车</div>
      <div class="back">
        <van-icon name="wap-home-o" @click="handleHome" />
      </div>
    </div>
    <div id="main">
      <div class="empty" v-if="isLogin" v-show="!mygoods">
        <img
          src="https://mfs.ys7.com/mall/1b34854bd8f0bf0f0e1cb1f6bb9a7164.png"
          alt=""
        />
        <p>购物车还是空的</p>
        <router-link to="/home">去逛逛</router-link>
      </div>
      <div class="empty" v-if="!isLogin">
        <img
          src="https://mfs.ys7.com/mall/06b30f30f366b3e315ea73038fd2f81a.png"
          alt=""
        />
        <p>登录下，精彩内容等你发现</p>
        <router-link to="/login">登录</router-link>
      </div>
      <div class="goodsList" v-if="isLogin && mygoods">
        <p v-if="!isShow" @click="handleEdit">编辑</p>
        <p v-if="isShow" @click="handleEditEnd">完成</p>
        <div class="discounts">
          <div class="top">
            <h2>
              <span>优惠</span>
              <strong>[满减]</strong>
              <em>每满200减30</em>
            </h2>
            <van-icon @click="isDown = !isDown" name="arrow-down" />
          </div>
          <h1 v-if="isDown">
            <strong>[满减]</strong
            >满100减10,满200减20,<em>满300减40</em>,满600减70,满900减100,满1200减130,满1500减160,满1800减190,满2100减220,满2400减250<br />
            <strong>[包邮]</strong>满198包邮
          </h1>
        </div>
        <div
          class="product"
          v-for="(itm, index) in mygoods"
          :key="index"
        >
          <input
            type="checkbox"
            :checked="itm.isChecked"
            @click="handleChangeChecked({isShow,bool:itm.isChecked,_id:itm._id,index, type: 'oneChange' })"
            name=""
            id=""
          />
          <img :src="itm.gdetail.image_url" alt="" />
          <div class="detail">
            <p>{{ itm.gdetail.name }}</p>
            <h3 @click="handleGoodMenu(index)" class="showMenu">
              <span>{{ goodMenuShow[index].menu }}</span>
              <van-icon name="arrow-down" />
            </h3>
            <div class="price">
              <span>买贵退差</span>
              <h4>
                <strong>{{ goodMenuShow[index].nowprice }}</strong>
              </h4>
            </div>
            <div class="count">
              <h5>
                <strong>{{ goodMenuShow[index].oldprice }}</strong>
              </h5>
              <h6>
                <i
                  class="left"
                  @click="
                    handleChangeChecked({_id:mygoods[index]._id ,type: 'changeNum', rst: '-', index ,num: goodMenuShow[index].num-1})
                  "
                  :class="{ preEvent: goodMenuShow[index].num <= 1 }"
                  >-</i
                >
                <em>{{ goodMenuShow[index].num }}</em>
                <i
                  class="right"
                  @click="
                    handleChangeChecked({_id:mygoods[index]._id, type: 'changeNum', rst: '+', index ,num: goodMenuShow[index].num+1})
                  "
                  >+</i
                >
              </h6>
            </div>
            <h1>
              <strong>距活动结束</strong>
              <van-count-down
                class="timer"
                :time="time"
                format="DD 天 HH:mm:ss"
              />
            </h1>
          </div>
        </div>
      </div>

      <div class="recommended">
        <div class="line"></div>
        <div class="title">
          <img
            src="https://mfs.ys7.com/mall/e0211862ea7ffa12e4823a141ad32509.png"
            alt=""
          />
          <span>猜你喜欢</span>
        </div>
        <div class="allGoods">
          <div class="box" v-for="item in intrData" :key="item.goods_id">
            
            <div class="goods">
              <router-link :to="`/detail/${item.goods_id}`">
                    <img class="bigpic" :src="item.image_url" alt="" />
              <p>
                <img
                  src="	https://mfs.ys7.com/mall/11eb63949da4d5cf59b4c8e90d38c925.png"
                  alt=""
                />
                <span
                  >&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{{
                    item.name
                  }}</span
                >
                <em>{{ item.brief }}</em>
              </p>
              <div class="price">
                <h1>
                  ￥<span>{{ item.price2.low }}</span>
                </h1>
                <h2>
                  ￥<span>{{ item.price2.high }}</span>
                </h2>
              </div>
              </router-link>
              
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="checkout" v-if="isAlert">
      <div class="proCheck">
        <div class="checkTop">
          <img :src="mygoods[goodIndex].gtion.good_img" alt="" />
          <div class="text">
            <h3>
              <span>{{ price }}</span>
            </h3>
            <h1>{{ prices }}</h1>
          </div>
          <van-icon
            name="clear"
            size="0.25rem"
            color="#ccc"
            @click="handleClose"
          />
        </div>
        <div class="proMain">
          
          <h2>规格</h2>
          <div
            v-for="(item, index) in mygoods[goodIndex].gtion
              .good_spec"
            :key="index"
             class="line"
          >
            <div class="line">{{ item.spec_name }}</div>
            <p
              style="
                display: inline-block;
                border-radius: 0.8rem;
                margin-left: 0.1rem;
                padding: 0 0.08rem;
              "
              v-for="(text, i) in item.spec_item"
              :key="i"
              @click="handelChangeMenu(index, i)"
              :class="{ active: goodbgs[index] == text.spec_value_id }"
            >
              {{ text.value }}
            </p>
          </div>
          <h2  class="line">数量</h2>
          <div class="num">
            <em @click="handleChangeCount(false)">-</em>
            <strong>{{ this.goodCount }}</strong>
            <em @click="handleChangeCount(true)">+</em>
          </div>
        </div>
        <b @click="handleMakeSure">确定</b>
      </div>
    </div>
    <div id="footer" v-if="isCheckOut && !!mygoods">
      <div class="footerAll" v-if="!isShow">
        <div class="check">
          <input
            type="checkbox"
            :checked="cartData.isAllChecked"
            @click="
              handleChangeChecked({
                bool: cartData.isAllChecked,
                type: 'allChange',
                isShow,

              })
            "
            name=""
            id=""
          />
          <span>全选</span>
        </div>
        <div class="total">
          <div class="left">
            <div class="left_top">
              合计：
              <p>
                ￥<i>{{
                  countCheckedGoods.totalPrice - countCheckedGoods.redPrice
                }}</i>
              </p>
            </div>
            <div class="left_bottom">
              共优惠：
              <p>
                ￥<i>{{ countCheckedGoods.redPrice }}</i>
                <span v-show="countCheckedGoods.reduPrice >= 20">
                  （包邮）</span
                >
              </p>
            </div>
          </div>
          <router-link :to="`/checkout/${countCheckedGoods.totalPrice - countCheckedGoods.redPrice}`"
            >结算(<span>{{ countCheckedGoods.count }}</span
            >)</router-link
          >
        </div>
      </div>
      <div class="footerDel" v-if="isShow && !!mygoods">
        <div class="delete">
          <input
            type="checkbox"
            :checked="cartData.isAllChecked"
            @click=" handleChangeChecked({
                bool: cartData.isAllChecked,
                type: 'allChange',
                isShow,
              })
            "
            name=""
            id=""
          />
          <span>全选</span>
        </div>
        <p
          @click="
            handleChangeChecked({
              where: countCheckedGoods.checkedIdArr,
              type: 'delete',
            })
          "
        >
          删除({{ countCheckedGoods.count }})
        </p>
        <p @click="handleEditEnd">确定</p>
      </div>
    </div>
  </div>
</template>

<script>
import request from "../utils/request";
import { Toast } from "vant";
import { mapState, mapGetters, mapMutations, mapActions } from "vuex";
export default {
  data() {
    return {
      intrData: null, //推荐数据
      isShow: false, //删除框显示
      time: 180 * 60 * 60 * 1000,
      isDown: false, //优惠券显示隐藏
      isAlert: false, //商品选择框显示隐藏
      isCheckOut: true, //footer显示隐藏控制
      num: 0, //规格选择
      isLogin: false,
      goodIndex: -1,
      goodbgs: null,
      goodCount: 0,
      oldCartGoods:null,
    };
  },
  computed: {
    isAllShow() {
      let bool = false;
      if (!sessionStorage.userinfo) {
        bool = true;
      } else if (this.mygoods) {
        bool = true;
      }
      return bool;
    },
    price() {
      let result = "";
      let that = this.mygoods[this.goodIndex];
      if (this.goodbgs.indexOf(0) != -1) {
        result = that.gtion.good_price.sale_price_desc;
      } else {
        let priObj = JSON.parse(that.gtion.spec_info.info.replace(/\\/, ""));
        let priObjMatch = JSON.parse(
          that.gtion.spec_info.is_buy.replace(/\\/, "")
        );
        for (var i in priObjMatch) {
          if (priObjMatch[i].toString() == this.goodbgs.slice().toString()) {
            result = "￥" + priObj[i].sale_price;
            break;
          }
        }
      }
      return result;
    },
    prices() {
      let result = "";
      let that = this.mygoods[this.goodIndex];
      if (
        this.goodbgs.every((val) => {
          return val == 0;
        })
      ) {
        result = "请选择商品规格";
      } else {
        let str = "已选择：";
        this.goodbgs.forEach((val, idx) => {
          // console.log(val);
          if (val != 0) {
            for (
              let i = 0;
              i < that.gtion.good_spec[idx].spec_item.length;
              i++
            ) {
              if (that.gtion.good_spec[idx].spec_item[i].spec_value_id == val) {
                str += '"' + that.gtion.good_spec[idx].spec_item[i].value + '"';
              }
            }
          }
        });
        result = str;
      }
      return result;
    },
    goodMenuShow() {
      //在商品中显示的价格等变量
      let arr = [];
      this.mygoods.forEach((val) => {
        let result1 = "已选择：",
          result2 = "",
          result3 = "",
          obj = {};
        let that = val;
        that.bgs.forEach((val, idx) => {
          for (let i = 0; i < that.gtion.good_spec[idx].spec_item.length; i++) {
            if (that.gtion.good_spec[idx].spec_item[i].spec_value_id == val) {
              result1 +=
                '"' + that.gtion.good_spec[idx].spec_item[i].value + '"';
            }
          }
        });
        let priObj = JSON.parse(that.gtion.spec_info.info.replace(/\\/, ""));
        let priObjMatch = JSON.parse(
          that.gtion.spec_info.is_buy.replace(/\\/, "")
        );
        for (var i in priObjMatch) {
          if (priObjMatch[i].toString() == that.bgs.slice().toString()) {
            result2 = "￥" + priObj[i].sale_price;
            result3 = "￥" + Math.round(priObj[i].sale_price * 1.1);
            break;
          }
        }
        obj.menu = result1;
        obj.nowprice = result2;
        obj.oldprice = result3;
        obj.num = that.num;
        arr.push(obj);
      });
      return arr;
    },
    countCheckedGoods() {
      let arr = this.goodMenuShow;
      let count = 0,
        totalPrice = 0,
        checkedIdArr = [];
      this.mygoods.forEach((val, index) => {
        if (val.isChecked) {
          count += arr[index].num;
          totalPrice += arr[index].num * arr[index].nowprice.slice(1);
          checkedIdArr.push(this.mygoods[index]._id);
        }
      });
      let redPrice =count*68
      return { count, totalPrice, redPrice, checkedIdArr };
    },
    cartList() {
      return this.$store.state.cart.cartList;
    },
    goodList() {
      return this.$store.state.cart.goodList;
    },
    allInfo() {
      return this.$store.getters["cart/allInfo"];
    },
    ...mapGetters({
      cartData: "huang/cartData",
    }),
    ...mapState({
      mygoods: state => state.huang.cartGoods,
    }),
  },
  methods: {
    ...mapMutations({
      handleAllCheck:"huang/cartAllCheckMut"
    }),
    ...mapActions({
      handleChangeChecked: "huang/changeCheckedAct",
    }),
    handleEdit(){
      this.isShow = true;
      this.oldCartGoods = [...this.mygoods]
      console.log(this.oldCartGoods)
      setTimeout(()=>{
        this.$store.commit('huang/noneCheckedMut')
      },10000)
    },
    handleEditEnd(){
      this.isShow = false;
      this.$store.commit('huang/editEndMut',this.oldCartGoods)
      console.log(this.oldCartGoods)
    },
    handleHome() {
      this.$router.push("/home");
    },
    handleClose() {
      this.isAlert = false;
      this.isCheckOut = true;
    },
    handleGoodMenu(i) {
      this.isAlert = true;
      this.isCheckOut = false;
      this.goodIndex = i;
      this.goodbgs = [...this.mygoods[i].bgs];
      this.goodCount = this.mygoods[i].num;
    },
    handleChangeCount(bool) {
      bool ? this.goodCount++ : this.goodCount > 1 && this.goodCount--;
    },
    handelChangeMenu(ind, i) {
      let itemId =
        this.mygoods[this.goodIndex].gtion.good_spec[ind].spec_item[i]
          .spec_value_id;
      this.goodbgs[ind] == itemId
        ? this.goodbgs.splice(ind, 1, 0)
        : this.goodbgs.splice(ind, 1, itemId);
    },
    handleMakeSure() {
      if (
        this.goodbgs.every((val) => {
          return val != 0;
        })
      ) {
        let changedata = {
          index: this.goodIndex,
          bgs: [...this.goodbgs],
          num: this.goodCount,
          _id:this.mygoods[this.goodIndex]._id
        };
        let Idx = 2;
        this.$store.dispatch("huang/cartChangeAct", { Idx, changedata });
        this.isAlert = false;
        this.isCheckOut = true;
      } else {
        Toast.fail("选择商品规格");
      }
    },
  },
  created() {
    request.post("/yingshi/cart/relation-transfer").then((res) => {
      this.intrData = res.data.data.item;
    });
    sessionStorage.userinfo && (this.isLogin = true);
  },
};
</script>

<style src="../assets/css/shopping.css" scoped></style>
<style scoped>
.detail .showMenu {
  width: 1.8rem !important;
}
.detail .showMenu span {
  width: 1.6rem;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.preEvent {
  pointer-events: none !important;
  color: #aaa !important;
}
</style>